package com.ck.lock.common;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;



/**
 * @author ck
 * @date 2023/7/4 15:11
 */
public class Counter {
    private static ReentrantLock reentrantLock = new ReentrantLock();
    private static ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
    private static Lock readLock = reentrantReadWriteLock.readLock();
    private static Lock writeLock = reentrantReadWriteLock.writeLock();
    public Integer count=0;

    /**
     * 无锁
     */
    public void increase(){
        count++;
    }

    /**
     * synchronized 修饰方法
     */
    public synchronized void increaseForSynchronized(){
        count++;
    }

    public int getCount(){
        return count;
    }

    /**
     * 写锁
     */
    public  void increaseForWriteLock(){
        writeLock.lock();
        try {
            count++;
        }
        catch (Exception e){
            e.printStackTrace();
        }
        finally {
            writeLock.unlock();
        }
    }

    /**
     * 读锁
     * @return
     */
    public int getCountForReadLock(){
        readLock.lock();
        try {

        }
        catch (Exception e){
            e.printStackTrace();
        }
        finally {
            readLock.unlock();
        }
        return count;
    }

    /**
     * ReentrantLock锁
     */
    public  void increaseForReentrantLock() {
        reentrantLock.lock();
            try {
                count++;
            }
            catch (Exception e) {
                e.printStackTrace();
            }
            finally {
                 reentrantLock.unlock();
             }
    }

}
